// src/utils/versionUpdatePlugin.ts

import fs from 'fs';
import path from 'path';
import { Plugin } from 'vite';

const versionUpdatePlugin = (options: { version: string | number }): Plugin => {
  let outDir = '';

  return {
    name: 'version-update',

    configResolved(config) {
      outDir = config.build.outDir;
    },

    buildStart() {
      if (!outDir) {
        console.warn('Output directory not set, skipping version.json generation.');
        return;
      }

      const versionFilePath = path.join(outDir, 'version.json');
      const content = JSON.stringify({ version: options.version }, null, 2);

      try {
        const dir = path.dirname(versionFilePath);
        if (!fs.existsSync(dir)) {
          fs.mkdirSync(dir, { recursive: true });
        }

        fs.writeFileSync(versionFilePath, content);
        console.log(`Version file written to: ${versionFilePath}`);
      } catch (err) {
        console.error('Failed to write version.json:', err);
      }
    },
  };
};

export default versionUpdatePlugin; // ✅ 默认导出
